/**
 * 
 */
package org.rico.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.rico.server.cache.Cache;
import org.rico.server.cache.CacheManager;
import org.slf4j.Logger;

/**
 * sso-client 校验令牌
 * @author rico
 *
 */
public class TokenValidateHandler extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(TokenValidateHandler.class);
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String token = req.getParameter("token");
		String systemId = req.getParameter("systemId");
		
		// 检查token是否有效
		boolean result = validateToken(systemId, token);
		if(result) {
			resp.getWriter().write("true");
		} else {
			resp.getWriter().write("false");
		}
	}
	
	/**
	 * 检查token是否有效
	 * @param systemId
	 * @param token
	 * @return
	 */
	private boolean validateToken(String systemId, String token) {
		logger.info("TokenVerifyHandler.verifyToken[systemId={}, token={}]", systemId, token);
		
		Cache cache = CacheManager.get(systemId);
		if(cache==null || StringUtils.isBlank(cache.getToken())) {
			return false;
		}
		
		if(!cache.getToken().equals(token)) {
			return false;
		}
		
		return true;
	}
	
}
